#include "fenetrerecrutement.h"

FenetreRecrutement::FenetreRecrutement(Joueur *J2, QWidget *p):QDialog(p)
{
    J=J2;
}


bool FenetreRecrutement::run()
{

    QFormLayout form(this);
    QString question =tr("Vous pouvez recruter %1 garde(s) :").arg(J->getFer());
    form.addRow(new QLabel(question));
    QList<QSpinBox *>fields;
    int max;
    for(int i = 0; i < J->v.size(); ++i)
    {
        if(J->v.value(i)->getUnites()<LIMIT_UNIT)
        {
            QSpinBox *nbUnit = new QSpinBox(this);
            max=min(LIMIT_UNIT-J->v.value(i)->getUnites(), J->getFer());
            nbUnit->setRange(0,max);
            QString nomV = J->v.value(i)->getNom();
            form.addRow(nomV, nbUnit);
            fields << nbUnit;
        }
    }
    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
                               Qt::Horizontal, this);
    form.addRow(&buttonBox);
    QObject::connect(&buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
    QObject::connect(&buttonBox, SIGNAL(rejected()), this, SLOT(reject()));

    if(this->exec()== QDialog::Accepted)
    {
        int somme=0;
        foreach (QSpinBox * nbUnit, fields)
        {
            somme+=nbUnit->value();
        }
        if(somme>J->getFer())
        {
            QMessageBox::critical(this, "Recruter", "Vous n'avez pas assez de Fer");
            return false;
        }
        else
        {
            int j=0;
            foreach (QSpinBox * nbUnit, fields)
            {
                while(J->v.value(j)->getUnites()>LIMIT_UNIT)
                {
                    j++;
                }
                J->v.value(j)->setUnites(nbUnit->value());
                j++;
            }
            J->setGardes(somme);
            return true;
        }
    }
    return false;
}
